package com.ruoyi.sale.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.company.domain.*;
import com.ruoyi.company.service.*;
import com.ruoyi.company.utils.Util;
import com.ruoyi.expressdelivery.domain.ExpressDelivery;
import com.ruoyi.expressdelivery.service.ExpressDeliveryService;
import com.ruoyi.procurement.service.ProcurementServer;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.product.service.ProductServer;
import com.ruoyi.productProof.domain.ProductProof;
import com.ruoyi.productProof.service.ProductProofService;
import com.ruoyi.purchase.domain.PurchaseModel;
import com.ruoyi.purchase.domain.PurchaseOrder;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.sale.domain.SaleGoodsModel;
import com.ruoyi.sale.domain.SaleorderModel;
import com.ruoyi.sale.domain.SaleorderOrder;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.scope.service.ScopeService;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.mapper.SysLogininforMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author WangChangShuo
 * 销售订单
 * @date 2022年05月09日 17:44
 */
@RestController
@RequestMapping("/business/saleorder")
public class SaleorderController extends BaseController {

    @Autowired
    ISaleorderService iSaleorderService;

    @Autowired
    ISysDeptService iSysDeptService;

    @Autowired
    ISysUserService iSysUserService;

    @Autowired
    PurchaseOrderService purchaseOrderService;

    @Autowired
    ICompanyOtherServer iCompanyOtherServer;

    @Autowired
    ICompanyInvoiceService iCompanyInvoiceService;

    @Autowired
    ICompanyLinkmanServer iCompanyLinkmanServer;

    @Autowired
    ProductServer productServer;

    @Autowired
    AuditService auditService;

    @Autowired
    ICompanyServer iCompanyServer;

    @Autowired
    ICompanyScopeServer iCompanyScopeServer;

    @Autowired
    ScopeService scopeService;

    @Autowired
    ProductProofService productProofService;

    @Autowired
    ICompanyMyLinkmanServer iCompanyMyLinkmanServer;

    @Autowired
    ExpressDeliveryService expressDeliveryService;

    @Autowired
    private ProcurementServer procurementServer;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SaleGoodsMapper saleGoodsMapper;

    @Autowired
    private SysLogininforMapper sysLogininforMapper;

    /**
     * 销售订单管理界面
     *
     * @return
     */
    @RequiresPermissions("business:saleorder:view")
    @GetMapping()
    public String getlist(Model model) {
        //查询客户名称
        List<SaleorderOrder> list = iSaleorderService.selectSaleorderDeptObj(ShiroUtils.getSysUser().getCompanyId());
        model.addAttribute("deptObj", list);
        return "sale/saleorder";
    }

    /**
     * 销售订单管理界面
     */
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo showlist(@RequestParam(value = "deptName", required = false) String deptName,
                                  @RequestParam(value = "beginTime", required = false) String beginTime,
                                  @RequestParam(value = "endTime", required = false) String endTime,
                                  @RequestParam(value = "saleorderStatus", required = false) String saleorderStatus) {

        startPage();
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        saleorderOrder.setBeginTime(beginTime);
        saleorderOrder.setEndTime(endTime);
        saleorderOrder.setDeptName(deptName);
        saleorderOrder.setSaleorderStatus(saleorderStatus);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long companyId = sysUser.getCompanyId();
        if (!sysUser.getDeptId().equals(companyId)) {
            saleorderOrder.setSaleorderUserId(sysUser.getUserId());
        }
        saleorderOrder.setDeptId(companyId);
        List<SaleorderOrder> list = iSaleorderService.selectSaleorderOrderList(saleorderOrder);
        return getDataTable(list);
    }

    @GetMapping("/logininforList")
    @ResponseBody
    public TableDataInfo logininforList(@RequestParam(value = "beginTime", required = false) String beginTime,
                                        @RequestParam(value = "endTime", required = false) String endTime) {

        startPage();
        SysLogininfor sysLogininfor = new SysLogininfor();
        sysLogininfor.setBeginTime(beginTime);
        sysLogininfor.setEndTime(endTime);
        sysLogininfor.setUserName(SecurityUtils.getUsername());
        List<SysLogininfor> list = sysLogininforMapper.logininforList(sysLogininfor);
        return getDataTable(list);
    }

    /**
     * 销售订单管理list
     */
    @GetMapping("/productList")
    @ResponseBody
    public TableDataInfo productList(@RequestParam(value = "productName", required = false) String productName,
                                     @RequestParam(value = "productType", required = false) String productType,
                                     @RequestParam(value = "deptId", required = false) Long deptId) {

        startPage();
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
        if (productName != null) {
            map.put("productName", productName);
        }
        if (productType != null) {
            map.put("productType", productType);
        }
        List<ProductModel> list = iSaleorderService.selectProductList(map);
        for (ProductModel productModel : list) {
            Map<String, Object> resMap = new HashMap<>();
            if (productType != null) {
                resMap.put("deptId", deptId);
                resMap.put("productType", productModel.getProductType());
                BigDecimal taxPrice = saleGoodsMapper.selectPrice(resMap);
                if (taxPrice != null) {
                    productModel.setTaxPrice(taxPrice.toBigInteger().longValue());
                }
            }

        }
        return getDataTable(list);
    }

    /**
     * 根据company 查询 公司名称
     */
    @PostMapping("/selectDeptNameById")
    @ResponseBody
    public String selectDeptNameById(@RequestParam("companyId") Long companyId) {
        String deptName = "";
        if (companyId != null) {
            SysDept sysDept = iSysDeptService.selectDeptById(companyId);
            deptName = sysDept.getDeptName();
        }
        return deptName;
    }

    /**
     * 根据company 查询 公司名称
     */
    @PostMapping("/selectUserNameById")
    @ResponseBody
    public String selectUserNameById(@RequestParam("userId") Long userId) {
        SysUser sysUser = iSysUserService.selectUserById(userId);
        return sysUser.getUserName();
    }

    /**
     * 新增销售订单时查询需要的数据
     */
    @GetMapping("/selectXsInformation")
    public Map<String, Object> selectXsInformation() {
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        Map<String, Object> resMap = new HashMap<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        //使用SimpleDateFormat的parse()方法生成Date
        SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
        String c = "";
        try {
            Date dates = a.parse(a.format(new Date()));
            c = String.format("%tY-%tm-%td", dates, dates, dates);
            saleorderOrder.setSaleorderNum(c);
            resMap.put("saleOrderNum", orderNum(dates, 1));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Long companyId = sysUser.getCompanyId();
        Long userId = sysUser.getUserId();
        Long deptId = sysUser.getDeptId();
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", companyId);
        Map<String, Object> maps = new HashMap();
        maps.put("deptId", companyId);
        if (!sysUser.getDeptId().equals(companyId)) {
            maps.put("userId", sysUser.getUserId());
        }

//      List<SysUser> sysUsers = iSysUserService.selectCustById(companyId);++
        List<SysUser> sysUsers = iSysUserService.selectCustByMap(maps);
        List<SysUser> user = iSysUserService.selectSalesmanList(companyId);
        //供应商
        int i = 0;
        if (!deptId.equals(companyId)) {
            if (sysUsers.size() != 0) {
                for (int i1 = user.size() - 1; i1 >= 0; i1--) {
                    if (!user.get(i1).getUserId().equals(userId)) {
                        user.remove(i1);
                        i++;
                    }
                }
            }
        }

        //model.addAttribute("users", i);
        resMap.put("users", i);
        Product product = new Product();
        product.setDeptId(sysUser.getCompanyId());
        Map<String, Object> map1 = new HashMap<>();
        map1.put("deptId", sysUser.getCompanyId());
        List<ProductModel> list = iSaleorderService.selectProductList(map1);
        if (sysUsers != null) {
            resMap.put("sysUsers", sysUsers);
        }
        //用户
        if (user != null) {
            resMap.put("user", user);
        }

        if (list != null) {
            resMap.put("products", list);
        }
        return resMap;
    }

    public String orderNum(Date date, int i) {
        i = 1;
        return purchaseOrderService.orderNum(date, i);
    }

    /**
     * 查询供应商的绑定业务员
     */
    @GetMapping("/selectUser")
    @ResponseBody
    public AjaxResult selectUser(@RequestParam("companyId") Long companyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
        map.put("companyId", companyId);
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther != null) {
            return AjaxResult.success(companyOther);
        } else {
            return AjaxResult.error("该公司没有合作单位请设置负责人信息");
        }
    }

    /**
     * 选择采购单界面
     */
    @GetMapping("/selectPurchase")
    public Map<String, Object> selectPurchase() {
        Map<String, Object> resMap = new HashMap<>();
        //根据当前登录人的公司id 去查询采购订单中的供应商信息
        resMap.put("SupplierObj", iSaleorderService.selectSaleGoodsSupplierObj(SecurityUtils.getLoginUser().getUser().getCompanyId()));
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", SecurityUtils.getLoginUser().getUser().getCompanyId());
        if (!SecurityUtils.getLoginUser().getUser().getDeptId().equals(SecurityUtils.getLoginUser().getUser().getCompanyId())) {
            map.put("userId", SecurityUtils.getLoginUser().getUser().getUserId());
        }
        resMap.put("SupplierObj", iSaleorderService.selectSaleGoodsSupplierObjMap(map));
        return resMap;
    }

    /**
     * 根据purchaseid 查询 采购订单编号
     */
    @PostMapping("/selectPurchaseById")
    @ResponseBody
    public JSONObject selectPurchaseById(@RequestParam("purchaseId") Long purchaseId) {
        JSONObject jsonObject = new JSONObject();
        PurchaseOrder purchaseOrder = purchaseOrderService.selectPurchaseOrderById(purchaseId);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(purchaseOrder);
        jsonObject.put("purchaseOrder", jsonArray);
        HashMap hashMap = new HashMap();
        hashMap.put("purchaseId", purchaseId);
        hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        List<PurchaseModel> purchaseModels = iSaleorderService.selectPurchaseModelById(hashMap);
        JSONArray jsonArray1 = new JSONArray();
        for (int i = 0; i < purchaseModels.size(); i++) {
            jsonArray1.add(purchaseModels.get(i));
        }

        jsonObject.put("purchaseModels", purchaseModels);
        return jsonObject;
    }

    /**
     * 选择产品界面
     */
    @GetMapping("/selectProduct/{index}")
    public String selectProduct(@PathVariable("index") int index, Model model) {
        model.addAttribute("index", index);
        return "sale/selectProduct";
    }


    /**
     * 下拉表格
     */
    @GetMapping("/tableSelect")
    @ResponseBody
    public JSONObject tableSelect(@RequestParam(value = "productType", required = false) String productType, @RequestParam(value = "deptId", required = false) Long deptId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        HashMap map = new HashMap();
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("deptId", deptId);
        resMap.put("productType", productType);
        map.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
        if (productType != null & !"".equals(productType)) {
            map.put("productType", productType);
        }

        List<ProductModel> productModels = iSaleorderService.selectTableList(map);
        BigDecimal taxPrice = saleGoodsMapper.selectPrice(resMap);

        jsonObject.put("count", productModels.size());
        JSONArray jsonArray = new JSONArray();
        Long amount = 0L;
        for (int i = 0; i < productModels.size(); i++) {
            ProductModel productModel = productModels.get(i);
            if (productModel.getSalesUnit().equals("盒")) {
                String b = productModel.getWarehousingNum();
                int c = Integer.valueOf(b);
                amount = c / productModel.getFactor();
            } else {
                amount = Long.valueOf(productModel.getWarehousingNum());
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("modelCode", productModel.getModelCode());
            jsonObject1.put("productId", productModel.getProduct().getProductId());
            jsonObject1.put("productName", productModel.getProduct().getProductName());
            jsonObject1.put("productType", productModel.getProductType());
            jsonObject1.put("unit", productModel.getSalesUnit());
            jsonObject1.put("manufacturerName", productModel.getManufacturerName());
            jsonObject1.put("taxPrice", taxPrice);
            jsonObject1.put("warehousingNum", amount);
            jsonObject1.put("amount", productModel.getAmount());
            jsonObject1.put("factor", productModel.getFactor());
            jsonObject1.put("scopeId", productModel.getScopeId());
            jsonArray.add(jsonObject1);
        }
        jsonObject.put("data", jsonArray);
        return jsonObject;
    }

    /**
     * 根据 ModelCode查询
     */
    @PostMapping("/selectProductModelByModelCode")
    @ResponseBody
    public ProductModel selectProductModelByModelCode(String modelCode) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("modelCode", modelCode);
        hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        ProductModel productModel = iSaleorderService.selectProductModelByModelCode(hashMap);
        if (productModel.getSalesUnit().equals("盒")) {
            List<Integer> list1 = procurementServer.selectProductType(productModel.getProductType());
            int a = list1.get(0);
            if (a != 0) {
                String b = productModel.getWarehousingNum();
                int c = Integer.valueOf(b);
                int amount = c / a;
                productModel.setWarehousingNum(String.valueOf(amount));
            }
        }
        return productModel;
    }

    /**
     * 根据 ModelCode查询
     */
    @PostMapping("/selectProductNameByProductId")
    @ResponseBody
    public Product selectProductNameByProductId(Long productId) {
        Product product1 = new Product();
        product1.setProductId(productId);
        product1.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        Product product = productServer.selectProductById(product1);
        return product;
    }

    @PostMapping("/selectcompany")
    @ResponseBody
    public List<ExpressDelivery> selectcompany(HttpServletRequest httpServletRequest) {
        String companyid = httpServletRequest.getParameter("companyId");
        List<ExpressDelivery> list = expressDeliveryService.selectcompany(companyid);
        return list;

    }

    @PostMapping("/selectProductType")
    @ResponseBody
    public List<Integer> selectProductType(HttpServletRequest request) {
        String productType = request.getParameter("productType");
        return procurementServer.selectProductType(productType);
    }

    /**
     * 新增保存销售订单
     */
    @RequiresPermissions("business:saleorder:add")
    @Transactional
    @Log(title = "新增保存销售订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(@RequestBody SaleorderOrder saleorderOrder, @RequestBody PurchaseOrder purchaseOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (saleorderOrder.getSaleorderModels() == null) {
            return AjaxResult.error("请选择要销售的产品");
        }

        String saleorderNum = saleorderOrder.getSaleorderNum();
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("saleorderNum", saleorderNum);
        map1.put("deptId", sysUser.getCompanyId());
        SaleorderOrder saleorderOrder1 = iSaleorderService.selectSaleorderByMap(map1);
        if (saleorderOrder1 != null) {
            //使用SimpleDateFormat的parse()方法生成Date
            SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
            Date dates = null;
            try {
                dates = a.parse(a.format(saleorderOrder.getSaleorderDate()));
//              dates = a.parse(a.format(new Date()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String s = orderNum(dates, 1);
            saleorderOrder.setSaleorderNum(s);
        }

        if (purchaseOrder.getPurchaseModel() != null) {
            saleorderOrder.setIsPurchase("1");
        }

        //创建采购订单
        saleorderOrder.setSaleorderStatus("0");
        saleorderOrder.setCreateBy(sysUser.getUserName());
        saleorderOrder.setDeptId(sysUser.getCompanyId());
        saleorderOrder.setTaxRate(saleorderOrder.getSaleorderModels().get(0).getTaxRate());
        int i = iSaleorderService.insertSaleorder(saleorderOrder);
        if (saleorderOrder.getSaleorderModels() != null) {
            iSaleorderService.insertSaleorderModel(saleorderOrder);
        }
        //添加审核订单
        Audit audit = new Audit();
        //销售订单Id
        audit.setOrderId(saleorderOrder.getSaleorderId());
        //登陆人的companyid
        audit.setCompanyId(sysUser.getCompanyId());
        //主表的含税金额
        audit.setTaxAmount(saleorderOrder.getSaleorderTaxamount());
        //业务员id
        audit.setUserId(saleorderOrder.getSaleorderUserId());
        //客户id
        audit.setSupplierId(saleorderOrder.getCompanyId());
        //订单编号
        audit.setOrderNum(saleorderOrder.getSaleorderNum());
        //0为销售订单
        audit.setOrderType("0");
        //状态0为 未审核
        audit.setAuditStatus("0");
        int insertAudit = auditService.insertAudit(audit);
        //如果选择了采购订单 根据订单编号 修改该采购订单 isCreateSale字段为1
   /*    if (saleorderOrder.getPurchaseId() != null) {
           HashMap hashMap = new HashMap();
           hashMap.put("purchaseId", saleorderOrder.getPurchaseId());
           iSaleorderService.updatePurchaseIsCreateSale(hashMap);
       }
*/

        if (purchaseOrder.getPurchaseModel() != null) {
            for (int j = 0; j < purchaseOrder.getPurchaseModel().size(); j++) {
                PurchaseModel purchaseModel = purchaseOrder.getPurchaseModel().get(j);
                //执行数量
                purchaseModel.setExecuteNum(purchaseModel.getExecuteNum() + purchaseModel.getNum());
                //可执行数量
                Long remainingNum = purchaseModel.getRemainingNum() - purchaseModel.getNum();
                purchaseModel.setRemainingNum(remainingNum);
                //不更新 purchaseNum
                purchaseModel.setPurchaseNum(-1);
                purchaseOrderService.updatePurchaseModel(purchaseModel);

            }
        }
        if (insertAudit >= 1 && i >= 1) {
            return toAjax(1);
        } else {
            return toAjax(-1);
        }
    }

    //,SaleorderOrder saleorderOrder
    @PostMapping("/updateWl")
    @ResponseBody
    public void update(HttpServletRequest request) {
        String saleordernum = request.getParameter("saleorderNum");
        //  String fhnr = request.getParameter("fhnr");
        String phone = request.getParameter("phone");
        String shdz = request.getParameter("shdz");
        String fname = request.getParameter("name");
        String remarks = request.getParameter("remarks");
        try {
            expressDeliveryService.updateWl(phone, shdz, fname, saleordernum, remarks);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @PostMapping("/insertwl")
    @ResponseBody
    public void insertwl(HttpServletRequest request) {
        String saleordernum = request.getParameter("saleorderNum");
        String crtime = getTime();
        String loginname = SecurityUtils.getLoginUser().getUser().getNickName();
        //  String fhnr = request.getParameter("fhnr");
        String phone = request.getParameter("phone");
        String shdz = request.getParameter("shdz");
        String fname = request.getParameter("name");
        String companyId = request.getParameter("companyId");
        Long id = Long.parseLong(companyId);
        String remarks = request.getParameter("remarks");
        try {
            expressDeliveryService.insertwl(phone, shdz, fname, saleordernum, remarks, id, crtime, loginname);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getTime() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        String time = dateFormat.format(date);
        return time;
    }

    /**
     * 选择采购订单列表 post
     */
    @GetMapping("/selectPurchaseOrderList")
    @ResponseBody
    public TableDataInfo list(@RequestParam(value = "beginTime", required = false) String beginTime,
                              @RequestParam(value = "endTime", required = false) String endTime,
                              @RequestParam(value = "companyId", required = false) Long companyId) {

        PurchaseOrder purchaseOrder = new PurchaseOrder();
        purchaseOrder.setBeginTime(beginTime);
        purchaseOrder.setEndTime(endTime);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        startPage();
        purchaseOrder.setSupplierId(sysUser.getCompanyId());
        purchaseOrder.setDeptId(companyId);
        if (!sysUser.getDeptId().equals(sysUser.getCompanyId())) {
            purchaseOrder.setUserId(sysUser.getUserId());
        }
        List<PurchaseOrder> list = iSaleorderService.selectPurchaseOrderList(purchaseOrder);
        for (PurchaseOrder purchaseOrder1 : list) {
            purchaseOrder1.setIsPurchase("1");
        }
        return getDataTable(list);
    }

    @GetMapping("/selectCompanyAddress")
    @ResponseBody
    public List<CompanyAddress> selectCompanyAddress(@RequestParam(value = "companyId", required = false) Long companyId) {
        List<CompanyAddress> list = iCompanyServer.selectCompanyAddress(companyId);
        return list;
    }

    /**
     * 修改销售订单
     */
    @GetMapping("/selectEdit")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    public Map<String, Object> edit(@RequestParam(value = "saleorderId", required = false) Long saleorderId) {

        Map<String, Object> resMap = new HashMap<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleorderId", saleorderId);
        hashMap.put("deptId", sysUser.getCompanyId());
        SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderById(hashMap);
        if (saleorderOrder.getSaleorderModels().get(0).getSaleorderModelId() == null) {
            List<SaleorderModel> list = new ArrayList();
            saleorderOrder.setSaleorderModels(list);
            resMap.put("saleorderOrder", saleorderOrder);
        } else {
            for (SaleorderModel saleorderModel : saleorderOrder.getSaleorderModels()) {
                if (saleorderModel.getUnit() == "盒" || saleorderModel.getUnit().equals("盒")) {
                    saleorderModel.setRemainingNum(Math.toIntExact(saleorderModel.getRemainingNum() / saleorderModel.getFactor()));
                }
            }
            resMap.put("saleorderOrder", saleorderOrder);
        }

        Long companyId = sysUser.getCompanyId();
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", companyId);
        Map<String, Object> maps = new HashMap();
        maps.put("deptId", companyId);
        if (!sysUser.getDeptId().equals(companyId)) {
            maps.put("userId", sysUser.getUserId());
        }

        List<SysUser> sysUsers = iSysUserService.selectCustByMap(maps);
        SysUser user = sysUserMapper.selectUserName(saleorderOrder.getSaleorderUserId());
        user.setUserName(user.getNickName());
        //供应商
        Product product = new Product();
        product.setDeptId(sysUser.getCompanyId());
        Map<String, Object> map1 = new HashMap<>();
        map1.put("deptId", sysUser.getCompanyId());
        List<ProductModel> list = iSaleorderService.selectProductList(map1);
        Company companyInvoice = iCompanyServer.selectByCompanyId(companyId);
        if (sysUsers != null) {
            resMap.put("sysUsers", sysUsers);
        }
        if (user != null) {
            resMap.put("user", user);
        }
        if (list != null) {
            resMap.put("products", list);
        }
        if (companyInvoice != null) {
            resMap.put("taxRate", companyInvoice.getTaxRate());
        }

        // 获取上一条临近的ID
        resMap.put("previousId", iSaleorderService.querypreviousId(saleorderId));
        // 获取下一条临近的ID
        resMap.put("nextId", iSaleorderService.queryNextId(saleorderId));
        return resMap;
    }

    /**
     * 修改保存销售订单
     */
    @RequiresPermissions("business:saleorder:edit")
    @Log(title = "修改保存销售订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody SaleorderOrder saleorderOrder, @RequestBody PurchaseOrder purchaseOrder) {
        if (saleorderOrder.getSaleorderModels() == null) {
            return AjaxResult.error("产品不能为空");
        }
        return toAjax(iSaleorderService.updateSaleorderOrder(saleorderOrder, purchaseOrder));
    }


    @Log(title = "审核销售订单", businessType = BusinessType.UPDATE)
    @GetMapping("/auditSale")
    @ResponseBody
    public AjaxResult auditSale(@RequestParam(value = "saleorderId", required = false) Long saleorderId,
                                @RequestParam(value = "saleorderStatus", required = false) String saleorderStatus) {
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        saleorderOrder.setSaleorderId(saleorderId);
        saleorderOrder.setSaleorderStatus(saleorderStatus);
        return toAjax(iSaleorderService.auditSale(saleorderOrder));
    }


    @GetMapping("/editStatus")
    @ResponseBody
    public AjaxResult editStatus(@RequestParam(value = "type", required = false) String type,
                                 @RequestParam(value = "saleorders") List<Long> saleOrders) {
        iSaleorderService.updateStatus(saleOrders, type);
        return toAjax(200);
    }


    /**
     * 删除销售订单
     */
    @RequiresPermissions("business:saleorder:remove")
    @Log(title = "删除销售订单", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{saleorderId}/{saleorderNum}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("saleorderId") Long saleorderId, @PathVariable("saleorderNum") String saleorderNum) {
        expressDeliveryService.deleteinformation(saleorderNum);
        return toAjax(iSaleorderService.deleteSaleOrderById(saleorderId));
    }

    /**
     * 查看销售订单
     */
    @GetMapping("/findSaleorder/{saleorderId}")
    public String findSaleorder(@PathVariable("saleorderId") Long saleorderId, ModelMap mmap) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleorderId", saleorderId);
        hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderById(hashMap);
        List<SaleorderModel> saleorderModels = saleorderOrder.getSaleorderModels();
     /*   for (SaleorderModel saleorderModel : saleorderModels) {
            if (saleorderModel.getAllNum() == 0) {
                saleorderModel.setSalesUnit(saleorderModel.getUnit());

            }

        }*/
        mmap.put("saleorderOrder", saleorderOrder);
//        SysUser sysUsers = iSysUserService.selectUserByDeptId(saleorderOrder.getCompanyId());
//        SysUser sysUsers = iSysUserService.selectUserByDeptId(saleorderOrder.getCompanyId());
        SysUser sysUser = iSysUserService.selectUserById(saleorderOrder.getSaleorderUserId());
        Product product = new Product();
        product.setDeptId(ShiroUtils.getSysUser().getCompanyId());
        Map<String, Object> map1 = new HashMap<>();
        map1.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        List<ProductModel> list = iSaleorderService.selectProductList(map1);
        if (saleorderOrder != null) {
            mmap.addAttribute("sysUsers", saleorderOrder.getDeptName());
        }
        if (sysUser != null) {

            mmap.addAttribute("user", sysUser);
        }
        if (list != null) {
            mmap.addAttribute("products", list);
        }
        String taxRate = "";

        if (saleorderOrder != null) {
            taxRate = saleorderOrder.getTaxRate();
        }
        mmap.addAttribute("taxRate", taxRate);
        return "sale/findSaleorder";
    }

    /**
     * 选择采购单 子表的数据
     */
    @GetMapping("/selectPurchaseModelList")
    @ResponseBody
    public TableDataInfo selectPurchaseModelList(@RequestParam(value = "purchaseId", required = false) Long purchaseId) {
        startPage();
        HashMap hashMap = new HashMap();
        hashMap.put("purchaseId", purchaseId);
        hashMap.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
        List<PurchaseModel> purchaseModels = iSaleorderService.selectPurchaseModelById(hashMap);
        for (PurchaseModel purchaseModel : purchaseModels) {
            if (purchaseModel.getUnit().equals("盒") || purchaseModel.getUnit() == "盒") {
                purchaseModel.setAmount(purchaseModel.getAmount() / purchaseModel.getFactor());
                purchaseModel.setAllNum(purchaseModel.getAllNum() / purchaseModel.getFactor().intValue());

            }
        }
        return getDataTable(purchaseModels);
    }

    /**
     * 根据销售订单生成销售合同ajax
     */
    @GetMapping("/dataIntoContract")
    @ResponseBody
    public JSONObject dataIntoContract(@RequestParam(value = "saleorderId", required = false) Long saleorderId) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleorderId", saleorderId);
        hashMap.put("deptId", sysUser.getCompanyId());
//        SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderById(hashMap);
        SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderByIdMap(hashMap);
        Company company = iCompanyServer.selectByCompanyId(saleorderOrder.getDeptId());
        //需方 信息;
        Company demanderData = iCompanyServer.selectByCompanyId(saleorderOrder.getCompanyId());
        Map<String, Object> linkMap = new HashMap<>();
        linkMap.put("deptId", sysUser.getCompanyId());
        linkMap.put("companyId", saleorderOrder.getCompanyId());

        //供方信息;
        Company purchaseData = iCompanyServer.selectByCompanyId(saleorderOrder.getDeptId());
        Map<String, Object> myLinkMap = new HashMap<>();
        myLinkMap.put("deptId", sysUser.getCompanyId());
        JSONObject jsonObject = new JSONObject();
        //合同编号 是销售订单的编号
        jsonObject.put("contractNo", saleorderOrder.getSaleorderNum());
        //供方
        jsonObject.put("purchaseName", iSysDeptService.selectDeptById(saleorderOrder.getDeptId()).getDeptName());
        //签订日期 contractDate
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        jsonObject.put("contractDate", fmt.format(saleorderOrder.getSaleorderDate()));
        //需方
        jsonObject.put("demander", iSysDeptService.selectDeptById(saleorderOrder.getCompanyId()).getDeptName());
        //签订地点
        Map map = new HashMap();
        map.put("deptId", saleorderOrder.getDeptId());
        map.put("companyId", saleorderOrder.getCompanyId());
        map.put("gradeStatus", "02");
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther == null) {
            new AjaxResult(AjaxResult.Type.ERROR, "您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
            throw new RuntimeException("您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
        }
        jsonObject.put("contractAddress", company.getRasCity());
        //销售订单产品
        JSONArray jsonArrayModel = new JSONArray();
        for (int i = 0; i < saleorderOrder.getSaleorderModels().size(); i++) {
            jsonArrayModel.add(saleorderOrder.getSaleorderModels().get(i));
        }
        jsonObject.put("models", jsonArrayModel);
        //总数量
        int totalNum = 0;
        for (int i = 0; i < saleorderOrder.getSaleorderModels().size(); i++) {
            totalNum += saleorderOrder.getSaleorderModels().get(i).getNum();
        }
        jsonObject.put("totalNum", totalNum);
        //总金额
        jsonObject.put("totalMoney", saleorderOrder.getSaleorderTaxamount());
        //合计人民币
        BigDecimal taxamount = saleorderOrder.getSaleorderTaxamount();
        double saleorderTaxamount = taxamount.doubleValue();
//        jsonObject.put("upperMoney", upperCase(saleorderTaxamount));
        jsonObject.put("upperMoney", Util.upperCases(saleorderTaxamount));
        //合同约定项
        JSONArray jsonContractTerms = new JSONArray();
        String contractTerms = companyOther.getContractTerms();
        //根据回车进行分割
        String[] contractTermsArr = new String[]{};
        if (!"".equals(contractTerms) && contractTerms != null) {
            contractTermsArr = contractTerms.split("\\r?\\n");
        }
        for (int i = 0; i < contractTermsArr.length; i++) {
            String str = contractTermsArr[i];
            jsonContractTerms.add(str);
        }
        jsonObject.put("contractTerms", jsonContractTerms);
        //供货单位
        //地址
        jsonObject.put("purchaseAddress", purchaseData.getRasProvince() + purchaseData.getRasCity() + purchaseData.getRasDistrict() + purchaseData.getRasAddress());
        //印章
        String purSeal = "";
        if (purchaseData.getElectronicSealUrl() != null && !"".equals(purchaseData.getElectronicSealUrl())) {
            purSeal = purchaseData.getElectronicSealUrl();
            purSeal = purSeal.split("/profile/upload")[1];
            try {
                purSeal = Util.encodeToString(RuoYiConfig.getUploadPath() + purSeal);
            } catch (IOException e) {
                e.printStackTrace();
            }
//            try {
//                purSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + purSeal);
//                String downloadPath = RuoYiConfig.getDownloadPath();
//                File file = new File(downloadPath);
//                if (!file.exists()) {
//                    file.mkdir();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        } else {
//            if (purchaseData.getSealUrl() != null && !"".equals(purchaseData.getSealUrl())) {
//                purSeal = purchaseData.getSealUrl();
//            } else {
////                //生成电子印章到服务器
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = purchaseData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String downloadPath = RuoYiConfig.getDownloadPath();
////                File file = new File(downloadPath);
////                if (!file.exists()) {
////                    file.mkdir();
////                }
////                File pngfile = new File(downloadPath + "/seal");
////                if (!pngfile.isDirectory()) {
////                    pngfile.mkdir();
////                }
////                String path = downloadPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(iSysDeptService.selectDeptById(purchaseData.getCompanyId()).getDeptName(), purchaseData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////                Company company2 = new Company();
////                company2.setSealUrl("/seal/" + imgname);
////                company2.setCompanyId(purchaseData.getCompanyId());
////                purSeal = "/seal/" + imgname;
////                //更新url
////                iCompanyServer.updateCompany(company2);
//            }
////            //将图片 转为64位 返回
////            try {
////                purSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + purSeal);
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
        }

        if (!purSeal.equals("")) {
            jsonObject.put("purSeal", "data:image/jpg;base64," + purSeal);
        }
        //邮编
        //电话
//        jsonObject.put("purchasePhone", purchaseInvoiceData.getCorporateRegisterPhone());
        jsonObject.put("purchasePhone", purchaseData.getCorporateRegisterPhone());
        //统一社会信用代码
        jsonObject.put("purchaseSocialCreditCode", purchaseData.getSocialCreditCode());
        //开户
        jsonObject.put("purchaseBank", purchaseData.getDepositBank());
        //账号
        jsonObject.put("purchaseBankNum", purchaseData.getBankNumber());
        //签约代表
//        jsonObject.put("purchaseCustomerForStaff", purchaseData.getCorporateRepresentative());
        jsonObject.put("purchaseCustomerForStaff", purchaseData.getCorporateRepresentative());
        //供货单位
        //地址
        jsonObject.put("demanderAddress", demanderData.getRasProvince() + demanderData.getRasCity() + demanderData.getRasDistrict() + demanderData.getRasAddress());
        //印章
        String demanderSeal = "";
        if (demanderData.getElectronicSealUrl() != null && !"".equals(demanderData.getElectronicSealUrl())) {
            demanderSeal = demanderData.getElectronicSealUrl();
            demanderSeal = demanderSeal.split("/profile/upload")[1];
            try {
                demanderSeal = Util.encodeToString(RuoYiConfig.getUploadPath() + demanderSeal);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
//            if (demanderData.getSealUrl() != null && !"".equals(demanderData.getSealUrl())) {
//                demanderSeal = demanderData.getSealUrl();
//                try {
//                    demanderSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + demanderSeal);
//                    String downloadPath = RuoYiConfig.getDownloadPath();
//                    File file = new File(downloadPath);
//                    if (!file.exists()) {
//                        file.mkdir();
//                    }
//                } catch (IOException e) {+
//                    e.printStackTrace();
//                }
//            } else {
////                //生成电子印章到服务器
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = demanderData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String downloadPath = RuoYiConfig.getDownloadPath();
////                File file = new File(downloadPath);
////                if (!file.exists()) {
////                    file.mkdir();
////                }
////
////                File pngfile = new File(downloadPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = downloadPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(iSysDeptService.selectDeptById(demanderData.getCompanyId()).getDeptName(), demanderData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////                Company company3 = new Company();
////                company3.setSealUrl("/seal/" + imgname);
////                company3.setCompanyId(demanderData.getCompanyId());
////                demanderSeal = "/seal/" + imgname;
////                //更新url
////                iCompanyServer.updateCompany(company3);
//            }
////            try {
////                demanderSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + demanderSeal);
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
        }
        if (!demanderSeal.equals("")) {
            jsonObject.put("demanderSeal", "data:image/jpg;base64," + demanderSeal);
        }
        //邮编
        //电话
//        jsonObject.put("demanderPhone", demanderInvoiceData.getCorporateRegisterPhone());
        jsonObject.put("demanderPhone", demanderData.getCorporateRegisterPhone());
        //统一社会信用代码
        jsonObject.put("demanderSocialCreditCode", demanderData.getSocialCreditCode());
        //开户
        jsonObject.put("demanderBank", demanderData.getDepositBank());
        //账号
        jsonObject.put("demanderBankNum", demanderData.getBankNumber());
        //签约代表
//        jsonObject.put("demanderCustomerForStaff", demanderData.getCorporateRepresentative());
        jsonObject.put("demanderCustomerForStaff", demanderData.getCorporateRepresentative());
        return jsonObject;
    }

    /**
     * 将金额转换为 大写
     *
     * @param money
     * @return
     */
    private String upperCase(double money) {
        String[] upNum = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
        String[] danwei = {"圆", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"};
        //取消科学记数法
        NumberFormat numFormat = NumberFormat.getInstance();
        numFormat.setMaximumFractionDigits(2);//设置小数位个数
        numFormat.setGroupingUsed(false);//取消科学技术发
        String formatNum = numFormat.format(money);
        String strmoney = formatNum + "";//浮点型转为字符型
        String lastUpNum = "null"; //用于存放上个参数的值
        String result = "";//返回的结果
        String[] split = strmoney.split("\\.");
        String strMoney = split[0];
        String point = "";
        //小数部分取值处理。
        if (split.length > 1) {
            point = split[1];
            if (point.length() == 1) {
                point = point.concat("0");
            }
        } else {
            point = "0";
        }
        //大于12位就直接返回。
        int moneyLen = strMoney.length();
        if (money == 0) {
            return "零圆整";
        }
        if (moneyLen > 12) {
            return "金额：" + money + "元，超出大写转换范围。最大金额：999999999999.99元";
        }
        //整数(integer)部分处理。
        if (!"0".equals(strMoney)) {
            for (int i = 0; i < moneyLen; i++) {
                String strNum = strMoney.charAt(i) + "";
                int singleNum = Integer.parseInt(strNum);
                String upSingleNum = upNum[singleNum];
                //上一为不等于0的情况
                if (!"零".equals(lastUpNum)) {
                    if (!"零".equals(upSingleNum)) {
                        result = result.concat(upSingleNum).concat(danwei[moneyLen - i - 1]);
                    } else
                        //为零但是在万、亿位上要加单位 (moneyLen-i)==9 指的是单位：亿。  (moneyLen-i)==5指的是单位：万
                        if ((moneyLen - i) == 5 || (moneyLen - i) == 9) {
                            lastUpNum = "";
                        } else {
                            result = result.concat(upSingleNum);
                        }
                }
                //上一位为0的情况
                if ("零".equals(lastUpNum) && !"零".equals(upSingleNum)) {
                    result = result.concat(upSingleNum).concat(danwei[moneyLen - i - 1]);
                }
                //捕捉上一位数（lastUpNum）为零的情况做优化。
                if ((moneyLen - i) == 5 || (moneyLen - i) == 9) {
                    //排除加单位时前面为"零"的情况。如：两百零万
                    if ("零".equals(lastUpNum) || "null".equals(lastUpNum)) {
                        result = result.substring(0, result.length() - 1);
                    }
                    if (!result.endsWith("亿")) {
                        result = result.concat(danwei[moneyLen - i - 1]);
                    }
                    lastUpNum = "";
                } else {
                    //把当前大写数字复制给 lastUpNum 用于下次判断
                    lastUpNum = upSingleNum;
                }
            }

            //对几万元整和几亿元整(result:五万零或者五亿零零)做优化。
            result = result.replaceAll("零零", "零");
            if (result.endsWith("零")) {
                String substring = result.substring(0, result.length() - 1);
                result = substring;
            }

            result = result.concat("圆");
            result = result.replaceAll("圆圆", "圆");
            result = result.replaceAll("万万", "万");
        }

        //小数(point)部分处理
        if ("0".equals(point)) {
            result = result + "整";
        } else {
            //去 整
//            if(result.endsWith("整")){
//                result = result.substring(0,result.length()-1);
//            }
            if ((point.charAt(0) + "").equals("0")) {
                result = result.concat(upNum[Integer.parseInt(point.charAt(1) + "")] + "分");
            } else if ((point.charAt(1) + "").equals("0")) {
                result = result.concat(upNum[Integer.parseInt(point.charAt(0) + "")] + "角");
            } else {
                result = result.concat(upNum[Integer.parseInt(point.charAt(0) + "")] + "角").concat(upNum[Integer.parseInt(point.charAt(1) + "")] + "分");
            }
        }
        return result;
    }

    /**
     * 根据 ModelCode查询
     */
    @PostMapping("/selectNewPrice")
    @ResponseBody
//    public AjaxResult selectNewPrice(Long productId, java.lang.String modelCode) {
//        HashMap hashMap = new HashMap();
//        hashMap.put("productId", productId);
//        hashMap.put("modelCode", modelCode);
//        hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
//        List<BigDecimal> price = iSaleorderService.selectSaleorderNewPrice(hashMap);
//        if (price.size() != 0) {
//            BigDecimal bigDecimal = price.get(0);
//
//            return AjaxResult.success("", bigDecimal.toString());
//        } else {
//            return AjaxResult.error();
//        }
//    }

    public String selectNewPrice(Long productId, String modelCode) {
        HashMap hashMap = new HashMap();
        hashMap.put("productId", productId);
        hashMap.put("modelCode", modelCode);
        hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        List<BigDecimal> price = iSaleorderService.selectSaleorderNewPrice(hashMap);
        if (price.size() != 0) {
            BigDecimal bigDecimal = price.get(0);
            return bigDecimal.toString();
        } else {
            return "";
        }
    }

    /**
     * 确认付款
     */
    @Transactional
    @Log(title = "销售订单确认付款", businessType = BusinessType.UPDATE)
    @GetMapping("/verifyPay/{saleorderId}/{status}")
    @ResponseBody
    public int agreeMessage(@PathVariable("saleorderId") Long saleorderId, @PathVariable("status") String status) {
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        saleorderOrder.setSaleorderId(saleorderId);
        saleorderOrder.setIsPay(status);
        int a = iSaleorderService.updateSaleorderOrderIsPay(saleorderOrder);
        if (a > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 确认废弃
     */
    @Transactional
    @Log(title = "销售订单确认废弃", businessType = BusinessType.UPDATE)
    @GetMapping("/abandonment/{saleorderId}")
    @ResponseBody
    public int abandonment(@PathVariable("saleorderId") Long saleorderId) {
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        saleorderOrder.setSaleorderId(saleorderId);
        saleorderOrder.setAbandonment("1");
        int a = iSaleorderService.updateSaleorderOrderIsAbandonment(saleorderOrder);
        if (a > 0) {
            return 1;
        } else {
            return 0;
        }

    }

    /**
     * 确认付款
     */
    @Transactional
    @Log(title = "销售订单确认付款", businessType = BusinessType.UPDATE)
    @PostMapping("/verifyInvoice/{saleorderId}")
    @ResponseBody
    public int verifyInvoice(@PathVariable("saleorderId") Long saleorderId) {
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        saleorderOrder.setSaleorderId(saleorderId);
        saleorderOrder.setIsInvoice("1");
        int a = iSaleorderService.updateSaleorderOrderIsPay(saleorderOrder);
        if (a > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 根据产品id  和 companyId  查询 该客户有无该产品的经营权限
     */
    @GetMapping("/selectIsInsideScopeByProductId")
    public String selectIsInsideScopeByProductId(@RequestParam("scopeId") Long scopeId, @RequestParam("companyId") Long companyId) {
        //先根据 productId 查 该产品的注册证信息
        boolean flag = true;
        HashMap hashMap = new HashMap();
        hashMap.put("scopeId", scopeId);
        hashMap.put("companyId", companyId);
        CompanyScope companyScope = iCompanyScopeServer.selectScopeBySortAndDeptId(hashMap);
        if (companyScope == null) {
            flag = false;
        }
        if (flag) {
            return "success";
        } else {
            return "false";
        }

    }

    /**
     * 采购验证产品范围
     * 根据产品id  和 当前登陆人公司  查询 该客户有无该产品的经营权限
     */
    @PostMapping("/selectPurchaseIsInsideScopeByProductId")
    @ResponseBody
    public String selectPurchaseIsInsideScopeByProductId(Long productId) {
        //先根据 productId 查 该产品的注册证信息
        List<ProductProof> list = productProofService.selectByProductId(productId);
        boolean flag = true;
        for (int i = 0; i < list.size(); i++) {
            ProductProof productProof = list.get(i);
            Long scopeId = productProof.getScopeId();
            //再根据companyId查 对方是否有该经营范围
            HashMap hashMap = new HashMap();
            hashMap.put("scopeId", scopeId);
            hashMap.put("companyId", ShiroUtils.getSysUser().getCompanyId());
            CompanyScope companyScope = iCompanyScopeServer.selectScopeBySortAndDeptId(hashMap);
            if (companyScope == null) {
                flag = false;
            }
        }
        if (flag) {
            return "1";
        } else {
            return "0";
        }
    }

    @PostMapping("/selectInformation")
    @ResponseBody
    public Map<String, Object> selectInformation(HttpServletRequest request) {
        Map<String, Object> resMap = new HashMap<>();
        String saleordernum = request.getParameter("saleorderNum");
        List<ExpressDelivery> list = new ArrayList<>();
        try {
            list = expressDeliveryService.selectInformation(saleordernum);
            if (list.size() == 0) {
                resMap.put("code", "-1");

            } else {
                resMap.put("code", "0");
                resMap.put("result", list);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resMap;
    }

    @PostMapping("/selectPdfUrlBySaleorderId")
    @ResponseBody
    public JSONArray selectPdfUrlBySaleorderId(Long saleorderId, HttpServletResponse response) {
        HashMap hashMap = new HashMap();
        hashMap.put("saleorderId", saleorderId);
        hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderById(hashMap);
        saleorderOrder.getPdfUrl().split("saleorderPdf");
        String pdfUrl = saleorderOrder.getPdfUrl();
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(pdfUrl);
        jsonArray.add(saleorderOrder.getSaleorderNum());

        return jsonArray;
    }


    @GetMapping("/downloadLodop")
    public void downloadBoM(HttpServletRequest request, HttpServletResponse response) {
        ClassLoader classLoader = SaleorderController.class.getClassLoader();
        URL url = classLoader.getResource("static/lodop/CLodop_Setup_for_Win32NT.exe");
        String fieldPath = url.toString();
        //定义变量
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        byte[] buffer = new byte[1024];
        //输出流
        //设置返回文件信息
        org.springframework.core.io.Resource resource = resourceLoader.getResource(fieldPath);
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        String fileName = "CLodop_Setup_for_Win32NT.exe";
        if (request.getHeader("user-agent").toLowerCase().contains("firefox")) {
            //火狐浏览器自己会对URL进行一次URL转码所以区别处理
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        } else {
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try (InputStream inputStream = resource.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(inputStream);
             OutputStream os = response.getOutputStream()) {
            //将内容使用字节流写入输出流中
            while (bis.read(buffer) != -1) {
                os.write(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
